<template>
  <div class="app-container">

    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="绿化" name="4"/>
      <el-tab-pane label="消杀" name="5"/>
    </el-tabs>

    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="planTitle">
        <el-input v-model="queryParams.planTitle" placeholder="请输入任务名称" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="所属小区" prop="estateId">
        <el-select v-model="queryParams.estateId" placeholder="请选择小区" style="width:140px;" size="mini" filterable
                   clearable>
          <el-option v-for="estate in estatesOptions"
                     :key="estate.id"
                     :label="estate.estateName"
                     :value="estate.id"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['module:eventPlan:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['module:eventPlan:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport"
                   v-hasPermi="['module:eventPlan:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" @click="selectDelete(1)" v-if="this.queryParams.isDel==0">查看禁用</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" @click="selectDelete(0)" v-if="this.queryParams.isDel==1">查看启用</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" :border="true" border
              @expand-change="((row,expandedRows)=>{expandChange(row,expandedRows)})">

      <el-table-column type="expand">
        <template #default="props">
          <el-table :data="props.row.workList" :border="childBorder">
            <!--            <el-table-column label="物业公司" align="center" prop="propertyName" width="200px"/>-->
            <!--            <el-table-column label="所属小区" align="center" prop="estateName" width="200px"/>-->
            <!--            <el-table-column label="所属计划" align="center" prop="planName" width="250px"/>-->
            <el-table-column label="所属任务" align="center" prop="eventTargetName" width="250px"/>
            <el-table-column label="开始时间" align="center" prop="beginTime"/>
            <el-table-column label="结束时间" align="center" prop="endTime"/>
            <el-table-column label="完成方式" align="center" prop="finishType" width="120px">
              <template slot-scope="scope">
                <div>
                  <el-tag v-if="scope.row.finishType === 0" effect="dark" style="cursor: pointer" :type="''">
                    任意一人完成
                  </el-tag>
                  <el-tag v-if="scope.row.finishType === 1" effect="dark" style="cursor: pointer" :type="''">
                    每人完成一次
                  </el-tag>
                  <el-tag v-if="scope.row.finishType === 2" effect="dark" style="cursor: pointer" :type="''">
                    指定人员完成
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="任务状态" align="center" prop="state" width="100px">
              <template slot-scope="scope">
                <div>
                  <el-tag v-if="scope.row.state === 0" effect="dark" style="cursor: pointer" :type="'info'">未完成
                  </el-tag>
                  <el-tag v-if="scope.row.state === 1" effect="dark" style="cursor: pointer" :type="''">进行中</el-tag>
                  <el-tag v-if="scope.row.state === 2" effect="dark" style="cursor: pointer" :type="'success'">已完成
                  </el-tag>
                  <el-tag v-if="scope.row.state === 3" effect="dark" style="cursor: pointer" :type="'danger'">已逾期
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="执行人" align="center" prop="workerSysUserName" width="350px"/>
            <el-table-column label="处理时间" align="center" prop="opTime" width="250px"/>
            <el-table-column label="处理结果" align="center" prop="opTime" width="150px">
              <template slot-scope="scope">
                <el-tag effect="dark" v-if="scope.row.state === 0" style="cursor: pointer" :type="'info'">查看结果
                </el-tag>
                <router-link v-if="scope.row.state != 0"
                             :to="'/property/survey/record?eventWorkId='+scope.row.id+'&eventType=4'" class="link-type">
                  <el-button icon="el-icon-back" size="mini">
                    查看结果
                  </el-button>
                </router-link>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="索引" align="center" prop="sort" width="70"/>
      <el-table-column label="任务名称" align="center" prop="planTitle" width="200"/>
      <el-table-column label="计划类型名称" align="center" prop="eventTypeName" width="130px"/>
      <el-table-column label="计划运作类型" align="center" prop="planType" width="150px">
        <template slot-scope="scope">
          <div>
            <el-tag v-if="scope.row.planType === 0" effect="dark" style="cursor: pointer" :type="''">自行作业</el-tag>
            <el-tag v-if="scope.row.planType === 1" effect="dark" style="cursor: pointer" :type="'info'">外包作业
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="巡视完成方式" align="center" prop="finishType" width="150px">
        <template slot-scope="scope">
          <div>
            <el-tag v-if="scope.row.finishType === 0" effect="dark" style="cursor: pointer" :type="''">
              每个区域必须巡视
            </el-tag>
            <el-tag v-if="scope.row.finishType === 1" effect="dark" style="cursor: pointer" :type="''">巡视人抽查
            </el-tag>
            <el-tag v-if="scope.row.finishType === 2" effect="dark" style="cursor: pointer" :type="''">巡视人不巡视
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="周期类型" align="center" prop="cycleType" width="100px">
        <template slot-scope="scope">
          <div>
            <el-tag v-if="scope.row.cycleType === 'day'" effect="dark" style="cursor: pointer" :type="''">按天</el-tag>
            <el-tag v-if="scope.row.cycleType === 'week'" effect="dark" style="cursor: pointer" :type="''">按周</el-tag>
            <el-tag v-if="scope.row.cycleType === 'month'" effect="dark" style="cursor: pointer" :type="''">按月
            </el-tag>
            <el-tag v-if="scope.row.cycleType === 'season'" effect="dark" style="cursor: pointer" :type="''">按季
            </el-tag>
            <el-tag v-if="scope.row.cycleType === 'half-year'" effect="dark" style="cursor: pointer" :type="''">半年
            </el-tag>
            <el-tag v-if="scope.row.cycleType === 'year'" effect="dark" style="cursor: pointer" :type="''">按年</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="计划开始时间" align="center" prop="beginTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划结束时间" align="center" prop="endTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="任务完成率" align="center" prop="percentage" width="150px">-->
<!--        <template slot-scope="scope">-->
<!--          {{ scope.row.percentage + "%" }}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <!--      <el-table-column label="任务开始时间" align="center" prop="beginRangeTime" width="100px"/>-->
      <!--      <el-table-column label="任务结束时间" align="center" prop="endRangeTime" width="100px"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="430px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-user-solid" @click="newUser(scope.row)">
            添加工作人员
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-user-solid">
            <router-link :to="'/event/eliminator/task?planId=' + scope.row.id + '&eventType='+queryParams.eventTypeId"
                         class="link-type">
              查看所属任务
            </router-link>
          </el-button>
          <!--          <el-button size="mini" type="text" icon="el-icon-user-solid">-->
          <!--            <router-link :to="'/event/leader?planId=' + scope.row.id + '&eventType='+scope.row.eventTypeId" class="link-type">-->
          <!--              查看负责人-->
          <!--            </router-link>-->
          <!--          </el-button>-->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['module:eventPlan:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateJicheng(scope.row)"
                     v-hasPermi="['module:eventPlan:edit']">继承</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['module:eventPlan:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="stateDelete(scope.row)"
                     v-hasPermi="['module:eventPlan:remove']">禁用/启用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改巡检执行计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属物业" prop="propertyId">
              <el-select v-model="form.propertyId" placeholder="请选择物业" style="width:100%" size="mini" filterable
                         clearable>
                <el-option v-for="property in propertyListOptions"
                           :key="property.id"
                           :label="property.propertyName"
                           :value="property.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属小区" prop="estateId">
              <el-select v-model="form.estateId" placeholder="请选择小区" style="width:100%" size="mini" filterable
                         clearable>
                <el-option v-for="estate in estatesOptions"
                           :key="estate.id"
                           :label="estate.estateName"
                           :value="estate.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planTitle">
              <el-input v-model="form.planTitle" placeholder="请输入任务名称" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="周期类型" prop="cycleType">
              <el-radio-group v-model="form.cycleType" size="mini">
                <el-radio v-for="dict in planCycleOption"
                          :key="dict.dictValue"
                          :label="dict.dictValue"
                          @change="gaibian()">{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="日期选择" v-if="form.cycleType=='week'">
              <el-checkbox-group v-model="form.cycleDay" size="mini">
                <el-checkbox v-for="week in weekList"
                             :key="week.dictValue"
                             :label="week.dictValue">{{ week.dictLabel }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="日期选择"
                          v-if="form.cycleType!='week'&&form.cycleType!=undefined&&form.cycleType!='day'">
              <el-select v-model="form.cycleDay" placeholder="日期选择" style="width:100%" size="mini" filterable
                         clearable multiple>
                <el-option v-for="month in monthDayList"
                           :key="month.dictValue"
                           :label="month.dictLabel"
                           :value="month.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-row v-for="(item, index) in form.eventPlanInfos" :key="item.id"
                    style="border: solid 1px;border-radius:5px;margin-top: 10px">
              <el-col :span="22">
                <el-row>
                  <el-col :span="12">
                    <!--                    <el-form-item label="执行事项" prop="eventPlanInfos.'+index+'.groupId"  style="width:100%;margin-top: 10px">-->
                    <!--                      <treeselect v-model="item.groupId" :options="groupOptions" :normalizer="normalizer" placeholder="请选择执任务" />-->
                    <!--                    </el-form-item>-->
                    <el-form-item label="执行事项" prop="eventPlanInfos.'+index+'.groupId"
                                  style="width:100%;margin-top: 10px;">
                      <el-select v-model="item.groupId" placeholder="请选择执行事项" style="width:95%;" size="mini"
                                 filterable clearable>
                        <el-option v-for="group in groupOptions"
                                   :key="group.id"
                                   :label="group.areaName"
                                   :value="group.id"/>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="执行人" prop="eventPlanInfos.'+index+'.userId"
                                  style="width:100%;margin-top: 10px;">
                      <el-select collapse-tags v-model="item.userId" placeholder="请选择执行人" style="width:95%;"
                                 size="mini" multiple filterable clearable>
                        <el-option v-for="user in sysUserList"
                                   :key="user.userId"
                                   :label="user.nickName"
                                   :value="user.sysUserId"/>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="完成方式" prop="eventPlanInfos.' + index+'.finishType" style="width: 100%;">
                      <el-select v-model="item.finishType" placeholder="请选择完成方式" size="mini">
                        <el-option label="任意一人完成" :value="0"/>
                        <el-option label="每人完成一次" :value="1"/>
                        <el-option label="指定人员完成" :value="2"/>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="任务时间" prop="eventPlanInfos.'+index+'.beginRangTime">
                      <el-input v-model="item.beginRangeTime" type="time" placeholder="任务开始时间" size="mini"
                                style="width: 100px;"></el-input>
                      <span> -- </span>
                      <el-input v-model="item.endRangeTime" type="time" placeholder="任务结束时间" size="mini"
                                style="width: 100px;"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="2">
                <div style="margin-top: 20px;">
                  <el-button @click.prevent="removeSetting(item)" size="mini">删除</el-button>
                </div>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-form-item label=" " style="margin-top: 10px">
              <el-button icon="el-icon-circle-plus-outline" @click="addSetting()" size="mini">新增设置</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="useable">
              <el-radio-group v-model="form.useable" size="mini">
                <el-radio :value="0" :label="0">禁用</el-radio>
                <el-radio :value="1" :label="1">开启</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划类型" prop="planType">
              <el-radio-group v-model="form.planType" size="mini">
                <el-radio :value="0" :label="0">自行作业</el-radio>
                <el-radio :value="1" :label="1">外包作业</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划时间" prop="dateRange">
              <el-date-picker v-model="form.dateRange" size="mini" style="width: 240px" value-format="yyyy-MM-dd"
                              type="daterange"
                              :picker-options="time_option" range-separator="-" start-placeholder="开始日期"
                              end-placeholder="结束日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leaderId">
              <el-select v-model="form.leaderId" placeholder="请选择负责人" style="width:100%;" size="mini" filterable
                         clearable>
                <el-option v-for="leader in sysUserList"
                           :key="leader.userId"
                           :label="leader.nickName"
                           :value="leader.sysUserId"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 修改巡检执行计划对话框 -->
    <el-dialog :title="title" :visible.sync="openUpdate" width="800px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属物业" prop="propertyId">
              <el-select v-model="form.propertyId" placeholder="请选择物业" style="width:100%" size="mini" filterable
                         clearable>
                <el-option v-for="property in propertyListOptions"
                           :key="property.id"
                           :label="property.propertyName"
                           :value="property.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属小区" prop="estateId">
              <el-select v-model="form.estateId" placeholder="请选择小区" style="width:100%" size="mini" filterable
                         clearable>
                <el-option v-for="estate in estatesOptions"
                           :key="estate.id"
                           :label="estate.estateName"
                           :value="estate.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planTitle">
              <el-input v-model="form.planTitle" placeholder="请输入任务名称" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="周期类型" prop="cycleType">
              <el-radio-group v-model="form.cycleType" size="mini">
                <el-radio v-for="dict in planCycleOption"
                          :key="dict.dictValue"
                          :label="dict.dictValue"
                          @change="gaibian()">{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="日期选择" v-if="form.cycleType=='week'">
              <el-checkbox-group v-model="form.cycleDay" size="mini">
                <el-checkbox v-for="week in weekList"
                             :key="week.dictValue"
                             :label="week.dictValue">{{ week.dictLabel }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="日期选择"
                          v-if="form.cycleType!='week'&&form.cycleType!=undefined&&form.cycleType!='day'">
              <el-select v-model="form.cycleDay" placeholder="日期选择" style="width:100%" size="mini" filterable
                         clearable multiple>
                <el-option v-for="month in monthDayList"
                           :key="month.dictValue"
                           :label="month.dictLabel"
                           :value="month.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-row v-for="(item, index) in form.eventPlanInfos" :key="item.id"
                    style="border: solid 1px;border-radius:5px;margin-top: 10px">
              <el-col :span="22">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="执行事项" prop="eventPlanInfos.'+index+'.groupId"
                                  style="width:100%;margin-top: 10px">
                      <el-select v-model="item.groupId" placeholder="请选择执行事项" style="width:95%;" size="mini"
                                 filterable clearable>
                        <el-option v-for="group in groupOptions"
                                   :key="group.id"
                                   :label="group.areaName"
                                   :value="group.id"/>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="任务时间" prop="eventPlanInfos.'+index+'.beginRangTime"
                                  style="width:100%;margin-top: 10px">
                      <el-input v-model="item.beginRangeTime" type="time" placeholder="任务开始时间" size="mini"
                                style="width: 100px;"></el-input>
                      <span> -- </span>
                      <el-input v-model="item.endRangeTime" type="time" placeholder="任务结束时间" size="mini"
                                style="width: 100px;"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <div
                  style="width: 14%;display: inline-block;vertical-align: top;text-align: right;font-weight: bold;margin-top: 10px">
                  执行人员
                </div>
                <div style="width: 86%;margin-bottom: 10px;display: inline-block;">
                  <el-tag type="button" closable v-for="(item1, index1) in item.userIds" :key="index1"
                          @close="deleteUser(item,item1,index1)" style="margin-left: 10px;margin-top: 10px">
                    {{ item.userName[index1] }}
                  </el-tag>
                  <el-tag type="button" @click="newUser(item)" style="margin-left: 10px;margin-top: 10px">
                    添加工作人员
                  </el-tag>
                </div>
              </el-col>
              <!--              <el-col :span="2">-->
              <!--                <div style="margin-top: 20px;">-->
              <!--                  <el-button @click.prevent="removeSetting(item)" size="mini">删除</el-button>-->
              <!--                </div>-->
              <!--              </el-col>-->
            </el-row>
          </el-col>

          <el-col :span="12" style="margin-top: 10px">
            <el-form-item label="状态" prop="useable">
              <el-radio-group v-model="form.useable" size="mini">
                <el-radio :value="0" :label="0">禁用</el-radio>
                <el-radio :value="1" :label="1">开启</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="margin-top: 10px">
            <el-form-item label="计划类型" prop="planType">
              <el-radio-group v-model="form.planType" size="mini">
                <el-radio :value="0" :label="0">自行作业</el-radio>
                <el-radio :value="1" :label="1">外包作业</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划时间" prop="dateRange">
              <el-date-picker v-model="form.dateRange" size="mini" style="width: 240px" value-format="yyyy-MM-dd"
                              type="daterange"
                              :picker-options="time_option" range-separator="-" start-placeholder="开始日期"
                              end-placeholder="结束日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leaderId">
              <el-select v-model="form.leaderId" placeholder="请选择负责人" style="width:100%;" size="mini" filterable
                         clearable>
                <el-option v-for="leader in sysUserList"
                           :key="leader.userId"
                           :label="leader.nickName"
                           :value="leader.sysUserId"/>
              </el-select>
            </el-form-item>

            <!--        <el-form-item label="巡视方式" prop="finishType">-->
            <!--          <el-radio-group v-model="form.finishType" size="mini">-->
            <!--            <el-radio :value="0" :label="0">全部巡视</el-radio>-->
            <!--            <el-radio :value="1" :label="1">抽查巡视</el-radio>-->
            <!--            <el-radio :value="2" :label="2">不巡视</el-radio>-->
            <!--          </el-radio-group>-->
            <!--        </el-form-item>-->
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!--        <el-button :loading="buttonLoading" size="mini" type="primary" @click="submitForm">确 定</el-button>-->
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="openNewUser" width="500px" append-to-body @close="cancel">
      <el-form ref="formNewUser" :model="formNewUser" :rules="rules" label-width="110px">
        <el-form-item label="执行事项" prop="groupId" style="width:100%;margin-top: 10px;">
          <el-select v-model="formNewUser.groupId" placeholder="请选择执行事项" style="width:95%;" size="mini"
                     filterable clearable>
            <el-option v-for="group in groupOptions"
                       :key="group.id"
                       :label="group.areaName"
                       :value="group.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="执行人" prop="userIds" style="width:100%;margin-top: 10px;">
          <el-select v-model="formNewUser.userIds" placeholder="请选择执行人" style="width:95%;" size="mini" multiple
                     filterable clearable>
            <el-option v-for="user in sysUserList"
                       :key="user.userId"
                       :label="user.nickName"
                       :value="user.sysUserId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="任务时间" prop="beginRangTime">
          <el-input v-model="formNewUser.beginRangeTime" type="time" placeholder="任务开始时间" size="mini"
                    style="width: 100px;"></el-input>
          <span> -- </span>
          <el-input v-model="formNewUser.endRangeTime" type="time" placeholder="任务结束时间" size="mini"
                    style="width: 100px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" size="mini" type="primary" @click="submitNewUserForm">确 定</el-button>
        <el-button @click="cancel1" size="mini">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPlan,
  getPlan,
  delPlan,
  addPlan,
  updatePlan,
  exportPlan,
  newWorkUser,
  getNightPlan,
  delectWorkUser,
  deletePlan
} from "@/api/module/event/plan";
import Template from "@/views/module/wx/template.vue";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listGroup} from "@/api/module/event/terminal/group";
import Treeselect from "@riophae/vue-treeselect";
import {listEventUser} from "@/api/module/estate/user";
import {listPropertyNoPage} from "@/api/module/property/property";
import {listAllEstate} from "@/api/module/estate/estate";
import {listWork} from "@/api/module/event/work";
import {listArea} from "@/api/module/event/area/cleanArea";
import {listList} from "@/api/module/event/area/areaList";

export default {
  name: "Plan",
  components: {Template, Treeselect},

  data() {
    return {
      activeName: '4',
      time_option: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      totalWork: 0,
      groupOptions: [],
      eventTypeOptions: [],
      planCycleOption: [],
      propertyListOptions: [],
      estatesOptions: [],
      // 巡检执行计划表格数据
      planList: [],
      weekList: [],
      sysUserList: [],
      monthDayList: [],
      workList: [],
      cycleDay: [],
      // 弹出层标题
      title: "",
      dataRow: [],
      // 是否显示弹出层
      open: false,
      openUpdate: false,
      openWork: false,
      openNewUser: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        eventTypeId: 4,
        isDel:0,
        estateId: undefined,
      },
      queryParamSys: {
        pageNum: 1,
        pageSize: 100,
      },
      queryParamWork: {
        pageNum: 1,
        pageSize: 10,
        eventPlanId: undefined,
      },
      queryParamUser: {
        eventType: 4,
        estateId: undefined,
      },
      queryAreaType: {
        areaType: 1,
        pageSize: 999,
      },
      // 表单参数
      form: {},
      formNewUser: {
        id: undefined,
        groupId: undefined,
        userId: undefined,
        beginRangeTime: undefined,
        endRangeTime: undefined,
        userIds: [],
      },
      // 表单校验
      rules: {
        propertyId: [
          {required: true, message: "请选择物业公司", trigger: "blur"}
        ],
        estateId: [
          {required: true, message: "请选择所属小区", trigger: "blur"}
        ],
        groupId: [
          {required: true, message: "请选择设备组", trigger: "blur"}
        ],
        userId: [
          {required: true, message: "请选择执行人", trigger: "blur"}
        ],
        planTitle: [
          {required: true, message: "请输入计划名称", trigger: "blur"}
        ],
        sort: [
          {required: true, message: "请输入排序", trigger: "blur"}
        ]

      }
    }
  },
  created() {
    this.getList();
    this.getEventTypeList();
    this.getEstateList();
    this.getDicts("plan_cycle_type").then(response => {
      this.planCycleOption = response.data;
    });
    this.getDicts("week_day").then(response => {
      this.weekList = response.data;
    });
    this.getDicts("month_day").then(response => {
      this.monthDayList = response.data;
    });
    this.getEstateList();
    this.getPropertyList();
    this.getSysUserList();
  },
  methods: {
    removeSetting(item) {
      var index = this.form.eventPlanInfos.indexOf(item)
      if (index !== -1) {
        this.form.eventPlanInfos.splice(index, 1)
      }
    },
    submitNewUserForm() {
      newWorkUser(this.formNewUser).then(response => {
        this.msgSuccess("新增成功");
        this.openNewUser = false;
        // this.getList();
        // this.reset();
        this.handleUpdate(this.dataRow);
      }).finally(() => {
        this.buttonLoading = false;
      });
    },
    expandChange(row, expandedRows) {
      console.log('expandChange', row) //当前行
      console.log('expandChange', expandedRows)//所有行

      getPlan(row.id).then(response => {

        console.log('this.planList', this.planList)
        for (let index in this.planList) {
          let plan = this.planList[index];
          console.log('plan', plan)
          console.log('row', row)
          if (row.id == plan.id) {
            this.planList[index].eventPlanInfos = response.data.eventPlanInfos;
            this.planList[index].workList = response.data.workList;
            this.planList[index].loading = false;
            break;
          }
        }

      });
    },
    addSetting() {
      this.form.eventPlanInfos.push({
        'groupId': '',
        'finishType': '',
        'userId': '',
        'beginRangeTime': '',
        'endRangeTime': ''

      })
    },
    getPropertyList() {
      listPropertyNoPage().then(response => {
        this.propertyListOptions = response.data;
      });
    },
    getEstateList() {
      listAllEstate().then(response => {
        this.estatesOptions = response.data;
      });
    },
    getSysUserList() {
      listEventUser(this.queryParamUser).then(response => {
        this.sysUserList = response;
      })
    },
    newUser(item) {
      // this.getTreeselect();
      this.openNewUser = true;
      console.log(item)
      // this.queryParamUser.estateId = row.estateId;
      // this.reset();
      this.formNewUser.id = item.planId;
      this.formNewUser.endRangeTime = item.endRangeTime;
      this.formNewUser.beginRangeTime = item.beginRangeTime;
      this.formNewUser.groupId = item.groupId;
    },
    handleClick(val) {
      console.log('handleClick', val.name);
      this.queryParamUser.eventType = val.name;
      this.activeName = val.name;
      this.queryParams.eventTypeId = parseInt(val.name);
      this.getList();
    },
    /** 查询巡检执行计划列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getEventTypeList() {
      this.loading = true;
      listPlan(this.queryParams).then(response => {
        this.eventTypeOptions = response.rows;
      });
    },
    gaibian() {
      this.form.cycleDay = [];
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.groupName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openUpdate = false;
      this.openWork = false;
      this.openNewUser = false;
      this.reset();
      this.dataRow = [];
    },
    cancel1() {
      this.openNewUser = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        propertyId: undefined,
        estateId: undefined,
        sort: undefined,
        planTitle: undefined,
        eventTypeId: 4,
        eventTypeName: "绿化",
        cycleType: undefined,
        cycleDays: undefined,
        beginRangeTime: undefined,
        endRangeTime: undefined,
        planType: undefined,
        finishType: undefined,
        beginTime: undefined,
        endTime: undefined,
        state: undefined,
        createTime: undefined,
        cycleDay: [],
        dateRange: [],
        eventPlanInfos: [],
        leaderId: undefined,
      }
      this.formNewUser = {
        id: undefined,
        groupId: undefined,
        userId: undefined,
        beginRangeTime: undefined,
        endRangeTime: undefined,
      }
      this.workList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // getTreeselect() {
    //   listGroup().then(response => {
    //     this.groupOptions = [];
    //     const data = { id: 0, groupName: '主类目', children: [] }
    //     data.children = this.handleTree(response.data, "id", "parentId");
    //     this.groupOptions.push(data);
    //   });
    // },

    getGroupOptions() {
      if (this.activeName == "4") {
        this.queryAreaType.areaType = 1;
      } else {
        this.queryAreaType.areaType = 2;
      }
      listList(this.queryAreaType).then(response => {
        this.groupOptions = response.rows;
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getGroupOptions();
      this.form.eventTypeId = this.queryParams.eventTypeId;
      if (this.form.eventTypeId == 4) {
        this.form.eventTypeName = "绿化"
      } else {
        this.form.eventTypeName = "消杀"
      }
      this.open = true;
      this.title = "添加绿化、消杀执行计划";
    },
    handleUpdateJicheng(row) {
      if (this.dataRow==undefined){
        this.reset();
      }
      this.dataRow = row;
      this.loading = true;
      // this.reset();
      const id = row.id || this.ids;
      getPlan(id).then(response => {

        for (var i=0;i<response.data.eventPlanInfos.length;i++){
          response.data.eventPlanInfos[i].userId=response.data.eventPlanInfos[i].userIds
        }
        // this.form.eventPlanInfos.userId = this.form.eventPlanInfos.userIds
        this.loading = false;
        this.form = response.data;
        this.form.id = undefined;
        this.form.dateRange=[];
        // this.form.beginTime = undefined;
        // this.form.endTime = undefined;
        this.form.sort = undefined;
        // console.log(this.form)
        // this.form.dateRange[0]=response.data.beginTime
        // this.form.dateRange[1]=response.data.endTime;
        this.queryParamUser.estateId = this.form.estateId;
        this.getGroupOptions();
        this.open = true;
        this.title = "修改巡检执行计划";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getGroupOptions();
      if (this.dataRow == undefined) {
        this.reset();
      }
      this.dataRow = row;
      this.loading = true;
      // this.reset();
      this.form.eventTypeId = this.queryParams.eventTypeId;
      if (this.form.eventTypeId == 4) {
        this.form.eventTypeName = "绿化"
      } else {
        this.form.eventTypeName = "消杀"
      }
      const id = row.id || this.ids;
      getPlan(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.form.dateRange[0] = response.data.beginTime
        this.form.dateRange[1] = response.data.endTime
        this.openUpdate = true;
        this.title = "修改绿化、消杀执行计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.dateRange.length === 2) {
            this.form.beginTime = this.form.dateRange[0] + " 00:00:00";
            this.form.endTime = this.form.dateRange[1] + " 00:00:00";
          }
          if (this.form.id != null) {
            console.log(this.form);
            updatePlan(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.reset();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            console.log(this.form)
            addPlan(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.reset();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    deleteUser(item, item1, index1) {
      this.$confirm('是否确认清除"' + item.userName[index1] + '"的任务?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        var infos = item;
        infos.delectUserId = item1;
        return delectWorkUser(infos);
      }).then(() => {
        this.loading = false;
        this.handleUpdate(this.dataRow)
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除绿化、消杀执行计划编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        return delPlan(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 禁用按钮操作 */
    stateDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认将删除绿化、消杀执行计划编号为"' + ids + '"的计划禁用?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        return deletePlan(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.msgSuccess("禁用成功");
      }).catch(() => {});
    },
    selectDelete(num) {
      this.queryParams.pageNum = 1;
      this.queryParams.isDel = num;
      this.getList();
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有绿化、消杀执行计划数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportPlan(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    }
  }
};
</script>

<style scoped>
.el-form-item {
  margin-bottom: 8px;
}

::v-deep .vue-treeselect__control {
  line-height: 30px;
  height: 30px;
}

::v-deep .el-form-item--medium .el-form-item__content {
  line-height: 30px;
  height: 30px;
}

::v-deep .vue-treeselect__single-value {
  line-height: 30px;
  height: 30px;
}
</style>
